package xuegao.study.mall.web.controller;

import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import xuegao.study.mall.common.api.CommonResult;
import xuegao.study.mall.web.config.AlipayConfig;
import xuegao.study.mall.web.domain.AlipayParam;
import xuegao.study.mall.web.service.AlipayService;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping(value = "/alipay")
public class AlipayController {

    @Autowired
    private AlipayConfig alipayConfig;

    @Autowired
    private AlipayService alipayService;

    @ApiOperation("支付宝电脑网站支付")
    @GetMapping(value = "/pay")
    public void pay(AlipayParam alipayParam, HttpServletResponse response) throws IOException {
        response.setContentType("text/html;charset=" + alipayConfig.getCharset());
        response.getWriter().write(alipayService.pay(alipayParam));
        response.getWriter().flush();
        response.getWriter().close();
    }

    @ApiOperation("支付宝手机网站支付")
    @GetMapping(value = "/webPay")
    public void webPay(AlipayParam alipayParam, HttpServletResponse response) throws IOException {
        response.setContentType("text/html;charset=" + alipayConfig.getCharset());
        response.getWriter().write(alipayService.webPay(alipayParam));
        response.getWriter().flush();
        response.getWriter().close();
    }

    @ApiOperation(value = "支付宝异步回调", notes = "必须为post请求,执行成功返回success,执行失败返回failure")
    @PostMapping(value = "/notify")
    public String notify(HttpServletRequest request) {
        Map<String, String> params = new HashMap<>();
        Map<String, String[]> requestParams = request.getParameterMap();
        for (String name : requestParams.keySet()) {
            params.put(name, request.getParameter(name));
        }
        return alipayService.notify(params);
    }

    @ApiOperation(value = "支付宝统一收单线下查询", notes = "订单支付成功返回交易状态:TRADE_SUCCESS")
    @GetMapping(value = "query")
    public CommonResult<String> query(String outTradeNo, String tradeNo) {
        String result = alipayService.query(outTradeNo, tradeNo);
        return CommonResult.success(result);
    }
}
